import axios, { AxiosRequestConfig } from '@ohos/axios'
import { Prompt } from '@kit.ArkUI'
import { AnyObject } from '../model/HttpModel'
import CryptoJS from '@ohos/crypto-js'


export interface ResponseType<T> {
  code: number;
  message: string;
  data: T;
  ok: boolean;
}

const request = axios.create({
  baseURL: 'http://192.168.2.127:6060', //'https://api.itouchtv.cn'
  timeout: 20000,
})

request.interceptors.request.use(
  (config) => {
   // const token = AppStorage.get<string>('token') as string
    const token = AppStorage.get<string>('token')
    if (token) {
      config.headers.token = token;
    }

    //  config.headers['X-ITOUCHTV-USER-ID'] = ''
    // config.headers['Authorization'] = ''

    // config.headers['X-ITOUCHTV-INSTALL-CHANNEL'] = 'AppStore'
    // config.headers['X-ITOUCHTV-RESOLUTION'] = '2532,1170'
    // config.headers['X-ITOUCHTV-CONN-TYPE'] = ''
    // config.headers['X-ITOUCHTV-OSVS'] = '17.5'

    // config.headers['X-ITOUCHTV-LATITUDE'] = '0.000000'
    // config.headers['X-ITOUCHTV-LONGITUDE'] = '0.000000'
    //aconfig.headers['X-ITOUCHTV-BRANCH'] = '0'

    // config.headers['X-ITOUCHTV-CONN-TYPE'] = ' WIFI'

    // config.headers['X-ITOUCHTV-A15'] = ''
    // config.headers['X-ITOUCHTV-A05 '] = '44'
    // config.headers['X-ITOUCHTV-A12'] = ''
    // config.headers['X-ITOUCHTV-A02'] = ''
    // config.headers['X-ITOUCHTV-Q31'] = '0'
    // config.headers['X-ITOUCHTV-A07'] = '440112'
    // config.headers['X-ITOUCHTV-A14'] = 'iPhone Simulator'
    // config.headers['X-ITOUCHTV-A04'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148,';
    // config.headers['X-ITOUCHTV-A01'] ='OPENUDID_a4722bc9967e0414ff2a7483afab00b407eec2d7'
    // config.headers['X-ITOUCHTV-A06'] ='4401'
    // config.headers['X-ITOUCHTV-A13'] =''
    // config.headers['X-ITOUCHTV-A16'] ='0'
    // config.headers['X-ITOUCHTV-Q31'] = '0'

    // config.headers['X-ITOUCHTV-APP-VERSION'] = '4.15.1'
    // config.headers['X-ITOUCHTV-Ca-Key'] = '71172577798798836911906857925786'
    // config.headers['X-ITOUCHTV-Ca-Timestamp'] = Date.now().toString(); //'1724404881733'//
    // config.headers['X-ITOUCHTV-Ca-Signature'] = appSignWithHttpMethod(config)
    // config.headers['X-ITOUCHTV-Ca-Key'] = '71172577798798836911906857925786'
    // config.headers['X-ITOUCHTV-CLIENT'] = 'NEWS_APP'

    return config
  }
)

function appSignWithHttpMethod(config: AxiosRequestConfig) {
  let method = config.method?.toUpperCase()
  let url: string = config.baseURL + config.url;
  let timestamp = config.headers['X-ITOUCHTV-Ca-Timestamp'];
  let appSign: string = method + '\n' + url + '\n' + timestamp + '\n'

  if (method === 'GET' || method === 'DELETE') {
    let query: string = ''
    let params = config.params['params']
    let pairs: string[] = []
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        let value = params[key];
        if (isNumber(value)) {
          value = value.toString()
        }
        let tmp = key + "=" + value
        pairs.push(tmp)
      }
    }
    query = pairs.join("&")
    appSign = method + '\n' + url + '?' + query + '\n' + timestamp + '\n'
    // GET
    // https://api.itouchtv.cn/liveservice/v13/homePageLives?channelId=530&channelOpHash=&pageNum=1&pageSize=10&preLiveAdHash=
    //   1724404028514

  } else if ((method === 'POST' || method === 'PUT') && !isObjectEmpty(config.params)) {
    let json = JSON.stringify(config.params)
    let contentMd5 = toMD5WithBase64(json);

    appSign = method + '\n' + url + '\n' + timestamp + '\n' + contentMd5
  }
  let appSecret = "1VP0NCmPa3KoL87FLJvCdbPaIJlqHOlce2ruxNL394UnsuygrzBGbDv7iqQo0Z5T"

  // appSign = 'GET\n' +
  //   'https://api.itouchtv.cn/liveservice/v13/homePageLives?channelId=530&channelOpHash=&pageNum=1&pageSize=10&preLiveAdHash=\n' +
  //   '1724404881733'
  appSign = hmacSha256(appSecret, appSign)

  //L0Qn/0Y+8j058a+/QQ+qvCTfQeguz5WIDa679esgYp0=
  // appsin:
  //   vgrMyqg/qWiouNPTFrPM5pBqHvzMrTR+Cs4BU2WUl5U=
  return appSign
}


request.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      return response.data.data
    } else {
      const message = response.data.message;
      Prompt.showToast({ message })
      return Promise.reject(message);
    }
  },
  (error) => {
    const message = error.message;
    Prompt.showToast({ message })
    return Promise.reject(message);
  }
)

export class Http {
  get<T>(url: string, params?: AnyObject) {
    return request.get<any, T>(url, { params })
  }

  post<T>(url: string, data?: AnyObject) {
    return request.post<any, T>(url, data)
  }

  put<T>(url: string, params?: AnyObject) {
    return request.put<any, T>(url, { params })
  }

  delete<T>(url: string, params?: AnyObject) {
    return request.delete<any, T>(url, { params })
  }
}


function isObjectEmpty(obj: object): boolean {
  return Object.keys(obj).length === 0;
}

function isString(value) {
  return typeof value == 'string'
}

function isNumber(value) {
  return typeof value == 'number'
}

function hmacSha256(passphrase: string, message: string,): string {

  let hash: string = CryptoJS.HmacSHA256(passphrase, message).toString(CryptoJS.enc.Base64);
  console.log(hash)
  return hash
}

function toMD5WithBase64(input: string): string {
  let hash: string = CryptoJS.MD5(input).toString(CryptoJS.enc.Base64);
  return hash
}


export const http = new Http()










